﻿using Avalonia;
using Avalonia.Controls;
using System;
using System.Collections.Generic;

namespace AvaloniaMVVM.Custom.Dialog
{
    public class DialogManager
    {
        private static readonly Dictionary<object, Visual> RegistrationMapper = new Dictionary<object, Visual>();

        static DialogManager()
        {
            RegisterProperty.Changed.AddClassHandler<Visual>(RegisterChanged);
        }

        private static void RegisterChanged(Visual sender, AvaloniaPropertyChangedEventArgs e)
        {
            if (sender is null)
            {
                throw new InvalidOperationException("The DialogManager can only be registered on a Visual");
            }
            if (e.OldValue != null)
            {
                RegistrationMapper.Remove(e.OldValue);
            }
            if (e.NewValue != null)
            {
                RegistrationMapper.Add(e.NewValue, sender);
            }
        }

        public static readonly AttachedProperty<object?> RegisterProperty = AvaloniaProperty.RegisterAttached<DialogManager, Visual, object?>("Register");

        public static void SetRegister(AvaloniaObject element, object value)
        {
            element.SetValue(RegisterProperty, value);
        }

        public static object? GetRegister(AvaloniaObject element)
        {
            return element.GetValue(RegisterProperty);
        }

        public static Visual? GetVisualForContext(object context)
        {
            return RegistrationMapper.TryGetValue(context, out var result) ? result : null;
        }

        public static TopLevel? GetTopLevelForContext(object context)
        {
            return TopLevel.GetTopLevel(GetVisualForContext(context));
        }
    }
}
